<template>
  <div>
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      :action="action"
      :data="data"
      multiple
      :drag="drag"
      :accept="accept"
      :auto-upload="autoUpload"
      :on-success="successFun"
      :on-progress="progressFun"
      :on-preview="previewFile"
      :on-error="errorFun"
      :on-remove="removeFile"
      :limit="limit"
      :on-exceed="exceedFun"
      :file-list="fileList"
      :headers="headers"
      :before-upload="beforeUpload"
      :disabled="disabled"
      :show-file-list="showFileList"
    >
      <i class="el-icon-upload" v-if="drag"/>
      <div v-if="drag" class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <div v-if="drag" slot="tip" class="el-upload__tip">
       {{ tip }}
      </div>
      <div v-else @click.stop="">
        文档预览
      </div>
    </el-upload>
    <el-dialog
      title="预览文件"
      :visible.sync="viewCoursewareVisible"
      append-to-body
      @close="closePopup"
      :key="popupKey"
    >
      <iframe
        width="800px"
        height="700px"
        :src="viewFileSrc"
        fit="contain"
        v-if="isPdf"
      ></iframe>
      <el-image
        v-if="isImg"
        style="width: 100%; height:auto"
        :src="viewFileSrc"
      ></el-image>
      <div ref="file" v-if="isWord" style="width: 800px; height: 800px"></div>
      <div v-if="isXlsx" style="width: 800px; height: 800px">
        <table border="1px solid #ccc">
          <thead>
            <tr>
              <th
                v-for="(cell, cellIndex) in title"
                :key="cellIndex"
                style="border: 1px solid #ccc"
              >
                {{ cell }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, index) in value" :key="index + 'A'">
              <td
                v-for="(v, index) in row"
                :key="index"
                style="padding: 15px 20px"
              >
                {{ v }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { resources, resources1 } from "@/api/specialWork/contractor.js";
import XLSX from "xlsx";
import axios from "axios";
import PDF from "vue-pdf";
const docx = require("docx-preview");
window.JSZip = require("jszip");
export default {
  data() {
    return {
      viewCoursewareVisible: false,
      viewFileSrc: "",
      isImg: false,
      isPdf: false,
      isWord: false,
      isXlsx: false,
      tableau: null,
      title: [],
      value: [],
      popupKey: Date.now(),
    };
  },
  components: { PDF },
  props: {
    drag: {
      type: Boolean,
      default: true,
    },
    action: {
      type: String,
      default: "",
    },
    accept: {
      type: String,
      default: "",
    },
    tip: {
      type: String,
      default: "",
    },
    data: {
      type: Object,
      default: function () {
        return {};
      },
    },
    successFun: {
      type: Function,
      default: () => () => {},
    },
    errorFun: {
      type: Function,
      default: () => () => {},
    },
    progressFun: {
      type: Function,
      default: () => () => {},
    },
    // previewFile: {
    //   type: Function,
    //   default: () => () => {},
    // },
    // exceedFun: {
    //   type: Function,
    //   default: () => () => {},
    // },
    autoUpload: {
      type: Boolean,
      default: false,
    },
    showFileList: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    removeFile: {
      type: Function,
      default: () => () => {},
    },
    beforeUpload: {
      type: Function,
      default: () => () => {},
    },
    limit: {
      type: Number,
      default: 1,
    },
    fileList: {
      type: Array,
      default: () => [],
    },
    headers: {
      type: Object,
      default() {
        return { Authorization: "Bearer " + getToken() };
      },
    },
  },
  methods: {
    closePopup() {
      this.popupKey = Date.now(); // 更新key值，强制重新加载组件
    },
    previewFile(file) {
      console.log('file',file);
      if (file.response) {
        this.viewFileSrc = process.env.VUE_APP_BASE_API + file.response.fileName;
        this.validateFile(file.response.fileName);
      } else {
        let url=file.fileUrl??file.url;
        this.viewFileSrc = process.env.VUE_APP_BASE_API + url;
        this.validateFile(url);     
      }
    },
    reset() {
      this.isImg = false;
      this.isPdf = false;
      this.isWord = false;
      this.isXlsx = false;
    },
    validateFile(file) {
      // console.log(file);
      this.reset();
      if (file.includes("pdf")) {
        this.isPdf = true;
        this.viewCoursewareVisible = true;
      } else if (file.includes("png") || file.includes("jpg")||file.includes('jpeg')) {
        this.isImg = true;
        this.viewCoursewareVisible = true;
      } else if (file.includes("docx")) {
        this.isWord = true;
        this.viewCoursewareVisible = true;
        this.resource(this.viewFileSrc);
      } else if (file.includes("xlsx") || file.includes("xls")) {
        this.isXlsx = true;
        this.viewCoursewareVisible = true;
        this.getXlsx(this.viewFileSrc);
      } else if (file.includes("doc")) {
        this.viewCoursewareVisible = false;
        this.$message.warning("暂不支持预览doc文件");
      }
    },
    resource(resource) {
      resources({ name: resource }).then((res) => {
        docx.renderAsync(res, this.$refs.file);
      });
    },
    getXlsx(url) {
      resources1({ name: url }).then((res) => {
        let workbook = XLSX.read(new Uint8Array(res), { type: "array" }); // 解析数据
        var worksheet = workbook.Sheets[workbook.SheetNames[0]]; // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表
        this.tableau = XLSX.utils.sheet_to_json(worksheet); // 渲染
        this.title = Object.keys(this.tableau[0]);
        this.tableau.forEach((v) => {
          this.value.push(Object.values(v));
        });
        console.log(this.value);
      });
    },
    exceedFun(){
      if(this.fileList&&this.fileList.length==this.limit){
        this.$message.warning(`当前限制选择 ${this.limit} 个文件`);
      }
    },
  },
};
</script>

<style lang="scss" scoped>

::v-deep .el-dialog .el-dialog__body{
  padding:0 20px 20px 20px !important;
}

</style>
